package com.zhongmeng.rxjava2test.presenter


import com.zhongmeng.rxjava2test.base.BaseModle
import com.zhongmeng.rxjava2test.base.BasePresenter
import com.zhongmeng.rxjava2test.modle.LoginModleImpl
import com.zhongmeng.rxjava2test.retrofit.ApiServiceManager
import com.zhongmeng.rxjava2test.view.LoginView

/**
 * author :rcw.
 * date :2017/10/11 10:59.
 * presenter的实现类，处理modle数据和view的数据展示
 */

class LoginPresenterImpl<T>(private val loginView: LoginView<T>?) : BasePresenter(), LoginPresenter, BaseModle.OnRequestListener<T> {

    private val loginModle: BaseModle

    init {
        loginModle = LoginModleImpl(this)
    }

    /**
     * 实现父类的方法
     */
    override fun login(which: Int) {
        val error: Boolean
        val name = loginView!!.userName
        val password = loginView.passWord
        if (name.isEmpty()) {//数据校验
            loginView.setUserNameError()
            error = false
        } else if (password.isEmpty()) {
            loginView.setPassWordError()
            error = false
        } else {//数据校验成功
            error = true
        }
        if (error) {//数据校验成功,Rxjava进行数据请求处理
            loginView.showProgress()
            //rx注册,成功后回调监听接口，view对返回数据进行展示
            addSubscription(loginModle.getObservable(ApiServiceManager.getCallBackData("db9fe289c32eeda773db291f29d9d461", name, password), which))
        }
    }

    override fun destory() {
        onUnsubscribe()
    }//rx取消注册

    /*override fun onRequestSuccess(data: Nothing?, which: Int) {
        if (loginView != null) {
            loginView.hideProgress()
            loginView.onSuccess(data, which)

        }
    }*/

    override fun onRequestSuccess(data: T, which: Int) {
        if (loginView != null) {
            loginView.hideProgress()
            loginView.onSuccess(data, which)

        }
    }

    override fun onRequestFail(throwable: Throwable) {
        if (loginView != null) {
            loginView.hideProgress()
            loginView.onFail(throwable)

        }
    }

}
